package tice.convert;


import java.text.NumberFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class Convert extends Activity{
 
    static class ViewHolder {
        TextView text;
        //ImageView icon;
    }
	
    private class Unit {
    	double data;
    	double formula;
    	String display;
    	String name;
    	int position;
    	
    	Unit(){
    		data = 0;
    		formula = 1;
    		name = "";
    		display = "0";
    		position = LIST_OFFSET;
    	}
    }
     
    final static double MIN_DOUBLE = 0.0000001;
    final static double MAX_DOUBLE = 1000000000;
    final static int MAX_NUMBER = 9;
	final static int LIST_OFFSET = 2;
	final static int DIALOG_TYPE_LIST = 1;
	static String PREFS_NAME = "tice.convert";
	static String PREFS_NAME_UPDATEDATE = "UpdateDate";
	
	int mMaskHeight = 0;
	Rect mMaskRect = null;
	TextView mMaskViewLeft = null;
	TextView mMaskNameLeft = null;
	TextView mMaskViewRight = null;
	TextView mMaskNameRight = null;
	ImageView mMaskLarge = null;
	boolean mTurnRight = true;
	boolean mScrollRight = false;
	boolean mScrollLeft = false;
	int mUnitType = 0;
	
	boolean mReInput = true;
	
	Unit mDataLeft, mDataRight;

	
	/** Called when the activity is first created. */
 	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
        	setContentView(R.layout.main_landscape);
        }else{
        	setContentView(R.layout.main);
        }
        
        mDataLeft = new Unit();
        mDataRight = new Unit();
        mMaskViewLeft = (TextView) findViewById(R.id.CenterLeft);
        mMaskViewRight = (TextView) findViewById(R.id.CenterRight);
        mMaskNameLeft = (TextView) findViewById(R.id.NameLeft);
        mMaskNameRight = (TextView) findViewById(R.id.NameRight);
        mMaskLarge = (ImageView) findViewById(R.id.MaskLarge);
        mMaskLarge.setOnClickListener(OnClickListenerMaskLarge);

        InitButtons();
    }

	@Override
	protected void onPause() {
		super.onPause();
		
        SharedPreferences settings = getSharedPreferences(Convert.PREFS_NAME, 0); 
        SharedPreferences.Editor editor = settings.edit(); 
        
        editor.putInt("mUnitType", mUnitType);
        editor.putInt("mRightPosition", mDataRight.position);
        editor.putInt("mLeftPosition", mDataLeft.position);
        editor.putBoolean("mTurnRight", mTurnRight);

        if(mTurnRight == true){
        	editor.putString("mDisplay", mDataLeft.display);
        }
        else{
        	editor.putString("mDisplay", mDataRight.display);
        }
        
        editor.commit();
	}
 	
 	@Override
    protected void onResume() {
        super.onResume();

        String tmp;
        SharedPreferences settings = getSharedPreferences(Convert.PREFS_NAME, 0);
        int type = settings.getInt("mUnitType", 0);
        int right = settings.getInt("mRightPosition", LIST_OFFSET);
        int left = settings.getInt("mLeftPosition", LIST_OFFSET);
        mTurnRight = settings.getBoolean("mTurnRight", true);
        tmp = settings.getString("mDisplay", "0");
    	tmp = tmp.replaceAll(",", "");
        tmp = tmp.length() == 0? "0" : tmp;
    	
        if(mTurnRight == true){
        	mDataLeft.display = tmp;
        	mDataLeft.data = Double.valueOf(tmp);
        }else{
        	mDataRight.display = tmp;
        	mDataRight.data = Double.valueOf(tmp);
        }

        
        LoadUnitView(type, right, left);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main,menu);

        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	super.onMenuItemSelected(featureId, item);
    	
    	switch(item.getItemId()) {
        case R.id.setting:
        	Intent i = new Intent(this, Setting.class);
            this.startActivity(i);
        	break;
        }
       
        return true;
    }		


 	private void LoadUnitView(int type,int right, int left){

 		mUnitType = type;
 		mDataRight.position = right;
 		mDataLeft.position = left;
 		
 		if(mUnitType == 0){
 			LoadCurrencyData();
 		}
 		
 		String title;
 		title = String.format("%s - %s",this.getResources().getText(R.string.app_name),UnitNames[mUnitType]);
 		this.setTitle(title);
 		
        ListView unitleft = (ListView)findViewById(R.id.Unit_Left);
        unitleft.setAdapter(new UnitAdapter(this,Units[mUnitType]));
        unitleft.setFadingEdgeLength(0);
        unitleft.setVerticalScrollBarEnabled(false);
        unitleft.setBackgroundColor(Color.WHITE);
        unitleft.setOnScrollListener(OnScrollListenerLeft);
        unitleft.setSelection(left - 2);
        unitleft.setSelected(false);
        mDataLeft.name = Units[mUnitType][left];
        mDataLeft.formula = formulae[mUnitType][left];
       
        ListView unitright = (ListView)findViewById(R.id.Unit_Right);
        unitright.setAdapter(new UnitAdapter(this,Units[mUnitType]));
        unitright.setFadingEdgeLength(0);
        unitright.setVerticalScrollBarEnabled(false);
        unitright.setBackgroundColor(Color.WHITE);
        unitright.setOnScrollListener(OnScrollListenerRight);
        unitright.setSelection(right - 2);
        unitright.setSelected(false);
        mDataRight.name = Units[mUnitType][right];	
        mDataRight.formula = formulae[mUnitType][right];
        
        ChangeMaskViewFontColor();
        UpdateMaskData();
        UpdateMaskView();
 	}
 	
 	private void LoadCurrencyData(){
 		int len = Currency.length - 2;

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

 		for(int i= 2;i< len;i++){
 			formulae[0][i] = settings.getFloat(Currency[i], Currency_default[i]);
 		}
 	}
 
 	public OnClickListener OnClickListenerMaskLarge = new OnClickListener (){

		@Override
		public void onClick(View v) {
			if (mTurnRight){
				mTurnRight = false;
				mDataRight.display = FormatOutput(mDataRight.data);
			} else {
				mTurnRight = true;
				mDataLeft.display = FormatOutput(mDataLeft.data);
			}
			
			ChangeMaskViewFontColor();
			mReInput = true;
		}
 	};
 		
 	private void UpdateLeftScrollView (AbsListView view){
 		
    	View t;	
    	ViewHolder h;
        int count = view.getChildCount();
        int oldoffset = 1000;
        int offset = 0;
        Rect r = new Rect();
        int first = view.getFirstVisiblePosition();
        boolean bfresh = false;
        
        for (int i=0; i<count; i++) {
        	t = (View)view.getChildAt(i);
        	t.getHitRect(r);
                
        	offset = Math.abs(r.top - mMaskRect.top);
        	
        	if (offset > oldoffset ) break;
        	if (offset < mMaskHeight ){
        		h = (ViewHolder)t.getTag();
        		
        		oldoffset = offset;
        		mDataLeft.position = first + i;
        		mDataLeft.formula = formulae[mUnitType][first + i];
        		mDataLeft.name = h.text.getText().toString();
        		
        		if ( mTurnRight == false){
        			mDataLeft.data = mDataRight.data / mDataRight.formula * formulae[mUnitType][first + i];
        		}
        		
        		bfresh = true;
        	}
        }
        
        if(bfresh == true){
    		UpdateMaskData();
    		UpdateMaskView();        	
        }
 	}
 	
 	public OnScrollListener OnScrollListenerLeft = new OnScrollListener (){
 		@Override
 		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,int totalItemCount){
 	    	
 			if(mScrollLeft == true){
 				if (firstVisibleItem == 0 || mMaskRect == null) return;
 				UpdateLeftScrollView(view);
 			}
 		}
		
 		@Override
	    public void onScrollStateChanged(AbsListView view, int scrollState) {

 	    	if (mMaskRect == null){
	    		mMaskRect = new Rect();
	    		mMaskLarge.getHitRect(mMaskRect);
	    		mMaskHeight = mMaskRect.height();
	    	}

	    	switch(scrollState){
    		case OnScrollListener.SCROLL_STATE_IDLE:
    			mScrollLeft = false;
    			UpdateLeftScrollView(view);
    			break;
    		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
    			mScrollLeft = true;
    			break;
    		case OnScrollListener.SCROLL_STATE_FLING:
    			mScrollLeft = false;
    			break;
	    	} 	    	
 		} 
 	};
 	
 	private void UpdateRightSrollView(AbsListView view){
 		
    	View t;
    	ViewHolder h;
        int count = view.getChildCount();
        int oldoffset = 1000;
        int offset = 0;
        Rect r = new Rect();
        int first = view.getFirstVisiblePosition();
        boolean bfresh = false;
        
        for (int i=0; i<count; i++) {
        	t = (View)view.getChildAt(i);
        	t.getHitRect(r);
                
        	offset = Math.abs(r.top - mMaskRect.top);
        	
        	if (offset > oldoffset ) break;
        	if (offset < mMaskHeight ){
        		h = (ViewHolder)t.getTag();
        		oldoffset = offset;
        		mDataRight.position = first + i;
        		mDataRight.formula = formulae[mUnitType][first + i];
        		mDataRight.name = h.text.getText().toString();
        		
        		if ( mTurnRight == true){
        			mDataRight.data = mDataLeft.data / mDataLeft.formula * formulae[mUnitType][first + i];
        		}

        		bfresh = true;
        	}
        } 
        
        if(bfresh == true){
    		UpdateMaskData();
    		UpdateMaskView();        	
        }
 	}
 	
 	public OnScrollListener OnScrollListenerRight = new OnScrollListener (){
 		@Override
 		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,int totalItemCount){
 			
 			if(mScrollRight == true){
 				if (firstVisibleItem == 0 || mMaskRect == null) return;
 				UpdateRightSrollView(view);
 			}
	    }
		
 		@Override
	    public void onScrollStateChanged(AbsListView view, int scrollState) {
	
	    	if (mMaskRect == null){
	    		mMaskRect = new Rect();
	    		mMaskLarge.getHitRect(mMaskRect);
	    		mMaskHeight = mMaskRect.height();
	    	}
	        
	    	switch(scrollState){
	    		case OnScrollListener.SCROLL_STATE_IDLE:
	    			mScrollRight = false;
	    			UpdateRightSrollView(view);
	    			break;
	    		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
	    			mScrollRight = true;
	    			break;
	    		case OnScrollListener.SCROLL_STATE_FLING:
	    			mScrollRight = false;
	    			break;
	    	}
	    } 
 	};
 	
 	private double ConvertTemperature(double data, double from, double to){
 		double value = 0, c = 0;
 		
 		switch ((int)from){
 		case 1:
 			c = data;
 			break;
 		case 2:
 			c = ( data - 32 ) * 5.0 / 9.0;
 			break;
 		case 3:
 			c = data - 273.5;
 			break;
 		case 4:
 			c = ( data - 492.3 ) * 5.0 / 9.0;
 			break;
 		}
 		
 		switch ((int) to){
 		case 1:
 			value = c;
 			break;
 		case 2:
 			value = c * 9.0 / 5.0 + 32;
 			break;
 		case 3:
 			value = c + 273.5;
 			break;
 		case 4:
 			value = c * 9.0 / 5.0 + 492.3;
 			break;
 		}
 		
 		return value;
 	}
 	
 	private void UpdateMaskData(){
 		
 		if ( mTurnRight == false){
 			if (mUnitType == 13){
 				mDataLeft.data = ConvertTemperature(mDataRight.data, mDataRight.formula, mDataLeft.formula);
 			}else{
 				mDataLeft.data = mDataRight.data / mDataRight.formula * mDataLeft.formula;
 			}
		} else {
			if (mUnitType == 13){
				mDataRight.data = ConvertTemperature(mDataLeft.data, mDataLeft.formula, mDataRight.formula );
			}else {
				mDataRight.data = mDataLeft.data / mDataLeft.formula * mDataRight.formula;
			}
		}
 	}

 	private void ChangeMaskViewFontColor(){
 		
		if ( mTurnRight == true){
			mMaskViewLeft.setTextSize(21);
			mMaskViewLeft.setTextColor(Color.BLACK);
			mMaskViewRight.setTextSize(18);
			mMaskViewRight.setTextColor(Color.DKGRAY);
	 		mMaskLarge.setBackgroundResource(R.drawable.mask_left);
	 		mMaskNameLeft.setTextColor(Color.WHITE);
	 		mMaskNameRight.setTextColor(0xff777777);
		}else{
			mMaskViewRight.setTextSize(21);
			mMaskViewRight.setTextColor(Color.BLACK);
			mMaskViewLeft.setTextSize(18);
			mMaskViewLeft.setTextColor(Color.DKGRAY);
	 		mMaskLarge.setBackgroundResource(R.drawable.mask_right);
	 		mMaskNameLeft.setTextColor(0xff777777);
			mMaskNameRight.setTextColor(Color.WHITE);
		}
		
		UpdateMaskView();
 	} 	
 	
 	private void UpdateMaskView(){
 		String str,disstr;
 		//double disdata;
 		
		if ( mTurnRight == true){
			//disstr = mDataLeft.display.length() == 0? "0": mDataLeft.display;
			//disstr = disstr.replaceAll(",", "");
			//disdata = Double.valueOf(disstr);
			//disstr = FormatOutput(disdata);
			disstr = FormatOutput(mDataLeft.data);
			mMaskViewLeft.setText(disstr);
			str = FormatOutput( mDataRight.data);
	 		mMaskViewRight.setText(str);
	 		mMaskNameLeft.setText(mDataLeft.name);
			mMaskNameRight.setText(mDataRight.name);
		}else{
			//disstr = mDataRight.display.length() == 0? "0": mDataRight.display;
			//disstr = disstr.replaceAll(",", "");
			//disdata = Double.valueOf(disstr);
			//disstr = FormatOutput(disdata);
			disstr = FormatOutput(mDataRight.data);
			mMaskViewRight.setText(disstr);
			str = FormatOutput( mDataLeft.data);
			mMaskViewLeft.setText(str);
			mMaskNameLeft.setText(mDataLeft.name);
			mMaskNameRight.setText(mDataRight.name);
		}
 	}
 	
 	private String FormatOutput(double data){
 		String output = "";
 		NumberFormat format = NumberFormat.getInstance();
 		int number = String.valueOf((int)data).length();
 		
 		double absdata = Math.abs(data);
 		
 		if (absdata == 0.0){
 			output = "0";
 		} else if ( absdata < MIN_DOUBLE){
 			output = String.format("%.3e",data);
 		}
 		else if(absdata < 1 && absdata >= MIN_DOUBLE){
	 		format.setMinimumFractionDigits(1);
	 		format.setMinimumIntegerDigits(1);
	 		format.setMaximumFractionDigits(7);
	 		format.setMaximumIntegerDigits(1);
	 		output = format.format(data);
 		}else if (absdata < MAX_DOUBLE){
	 		format.setMinimumFractionDigits(0);
	 		format.setMinimumIntegerDigits(1);
	 		format.setMaximumFractionDigits(MAX_NUMBER - 1 - number);
	 		format.setMaximumIntegerDigits(number);
	 		output = format.format(data);
 		}else {
 			output = String.format("%.3e",data);
 		}
 		
 		return output;
 	}
 	
 	private void PushData(int d){
 		
 		double data;
 		String strdata;
 		
 		if(mReInput == true){
 			strdata = "";
 			mReInput = false;
 		} else {
 			strdata = mTurnRight? mDataLeft.display : mDataRight.display;
 		}
 		
 		if(strdata.length() >= MAX_NUMBER && (d != -2 && d != -3)) return;
 		
 		int len = strdata.length();
 		
 		switch (d){
	 		case -1:{ //.
	 			if (strdata.lastIndexOf(".") == -1){
	 				if (len == 0){
	 					strdata = "0.";
	 				} else {
	 					strdata = strdata + ".";
	 				}
	 			}
	 			break;
	 		}
	 		case -2:{ //C
	 			if(len >= 1){
	 				int i = 1;
	 				if(len >= 2){
		 				if(strdata.lastIndexOf(".") == len - 2){
		 					i = 2;
		 				}
	 					if (len == 3 && strdata.charAt(0) == '0' ){
	 						i = 3;
	 					}
	 				}
	 				strdata = strdata.substring(0, strdata.length() - i);
	 			}else{
	 				strdata = "";
	 			}
	 			break;
	 		}
	 		case -3:{ //AC
	 			strdata = "";
	 			break;
	 		}
	 		case 0:{
	 			if (len == 0){
	 				break;
	 			}
	 		}
	 		default:{
	 			strdata = strdata + String.valueOf(d);
	 			break;
	 		}
 		}
 		
 		if (strdata.length() != 0){
 			data = Double.parseDouble(strdata);
 		}else{
 			data = 0;
 		}
 		
 		if(mTurnRight){
 			mDataLeft.data = data;
 			mDataLeft.display = strdata;
 		}else{
 			mDataRight.data = data;
 			mDataRight.display = strdata;
 		}
 		
 		UpdateMaskData();
 		UpdateMaskView();
 	}
 	
 	private void InitButtons(){
 		Button btn01 = (Button) findViewById(R.id.Button01);
 		Button btn02 = (Button) findViewById(R.id.Button02);
 		Button btn03 = (Button) findViewById(R.id.Button03);
 		Button btn04 = (Button) findViewById(R.id.Button04);
 		Button btn05 = (Button) findViewById(R.id.Button05);
 		Button btn06 = (Button) findViewById(R.id.Button06);
 		Button btn07 = (Button) findViewById(R.id.Button07);
 		Button btn08 = (Button) findViewById(R.id.Button08);
 		Button btn09 = (Button) findViewById(R.id.Button09);
 		Button btn00 = (Button) findViewById(R.id.Button00);
 		Button btn0D = (Button) findViewById(R.id.Button0D);
 		Button btn0C = (Button) findViewById(R.id.Button0C);
 		Button btnAC = (Button) findViewById(R.id.ButtonAC);
 		Button btnTYPE = (Button) findViewById(R.id.ButtonTYPE);
 		
 		btn01.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(1);
			}});
 		btn02.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(2);
			}});
 		btn03.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(3);
			}});
 		btn04.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(4);
			}});
 		btn05.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(5);
			}});
 		btn06.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(6);
			}});
 		btn07.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(7);
			}});
 		btn08.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(8);
			}});
 		btn09.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(9);
			}});
 		btn00.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(0);
			}});
 		btn0D.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(-1);
			}});
 		btn0C.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(-2);
			}});
 		btnAC.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				PushData(-3);
			}});
 		btnTYPE.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showDialog(DIALOG_TYPE_LIST);;
			}});
 		}
 	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_TYPE_LIST:
            return new AlertDialog.Builder(this)
            .setTitle("Choose Unit...")
            .setItems(UnitNames, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	LoadUnitView(which, LIST_OFFSET,LIST_OFFSET);
                }
            })
            .create();
        }
        return null;
    }
 	
/******************************************************************/
 	
    private class UnitAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private String[] mList;
        //private Bitmap mIcon;
        
        public UnitAdapter(Context context, String[] list) {
            mInflater = LayoutInflater.from(context);
            mList = list;
           //mIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
        }

        public int getCount() {
            return mList.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_left, null);

                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.text.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
                holder.text.setTextColor(Color.DKGRAY);
                holder.text.setPadding(0, 0, 5, 0);	
                holder.text.setBackgroundColor(Color.WHITE);
                //holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(mList[position]);

            return convertView;
        }
    }
    
    private static final String UnitNames[] = {"Currency","Angle","Area","Density","Electric Current","Energy",
    										   "Force", "Fuel Consumption", "Length", "Mass", "Power",
    										   "Pressure","Speed", "Temperature","Time","Volume"};
 	
    public static final String[] Currency = {
    		"", "",
    		"DZD",
    		"ARS",
    		"AUD",
    		"BHD",
    		"BOB",
    		"BWP",
    		"BRL",
    		"GBP",
    		"BND",
    		"CAD",
    		"KYD",
    		"CLP",
    		"CNY",
    		"COP",
    		"CRC",
    		"HRK",
    		"CZK",
    		"DKK",
    		"DOP",
    		"EGP",
    		"SVC",
    		"EEK",
    		"EUR",
    		"HNL",
    		"HKD",
    		"HUF",
    		"ISK",
    		"INR",
    		"IDR",
    		"ILS",
    		"JMD",
    		"JPY",
    		"JOD",
    		"KZT",
    		"KES",
    		"KRW",
    		"KWD",
    		"LVL",
    		"LBP",
    		"LTL",
    		"MKD",
    		"MYR",
    		"MUR",
    		"MXN",
    		"MDL",
    		"MAD",
    		"NAD",
    		"NPR",
    		"ANG",
    		"NZD",
    		"NIO",
    		"NGN",
    		"NOK",
    		"OMR",
    		"PKR",
    		"PGK",
    		"PYG",
    		"PEN",
    		"PHP",
    		"PLN",
    		"QAR",
    		"RUB",
    		"SAR",
    		"SCR",
    		"SLL",
    		"SGD",
    		"SKK",
    		"ZAR",
    		"LKR",
    		"SEK",
    		"TRY",
    		"CHF",
    		"TWD",
    		"TZS",
    		"THB",
    		"TTD",
    		"TND",
    		"USD",
    		"AED",
    		"UGX",
    		"UAH",
    		"UYU",
    		"VEB",
    		"VND",
    		"YER",
    		"ZMK",
    		"","",
    		};
    
    private static final float[] Currency_default = 
	    	{
    		0, 0, 
			72.70612f,
			3.8517983f,
			1.1896265f,
			0.37697014f,
			7.020007f,
			6.788866f,
			1.8810004f,
			0.6147793f,
			1.4387993f,
			1.0931004f,
			0.80999863f,
			551.26794f,
			6.8299947f,
			2036.6599f,
			584.79535f,
			5.1495957f,
			17.77588f,
			5.20969f,
			35.95053f,
			5.5289855f,
			8.749978f,
			10.949545f,
			0.699986f,
			18.890022f,
			7.7509165f,
			190.04181f,
			125.64393f,
			48.520138f,
			10000.0f,
			3.8200016f,
			88.05142f,
			93.615425f,
			0.70769906f,
			150.78407f,
			76.051414f,
			1245.33f,
			0.2871698f,
			0.4912991f,
			1501.5015f,
			2.4013004f,
			43.149944f,
			3.5214987f,
			31.549723f,
			13.247841f,
			11.222463f,
			7.922298f,
			7.760721f,
			75.872536f,
			1.7699993f,
			1.4611338f,
			19.919922f,
			154.01201f,
			6.036606f,
			0.3850093f,
			83.04958f,
			2.7472527f,
			4975.1245f,
			2.936004f,
			48.79001f,
			2.8601992f,
			3.6409976f,
			31.632557f,
			3.7500937f,
			12.550043f,
			3558.7188f,
			1.4419007f,
			21.087704f,
			7.7395186f,
			114.74469f,
			7.1057043f,
			1.4999993f,
			1.0607997f,
			32.879597f,
			1319.2612f,
			34.010136f,
			6.279987f,
			1.3224994f,
			1.0f,
			3.6729057f,
			2053.3882f,
			8.410005f,
			22.549948f,
			2145.9229f,
			17857.143f,
			202.18358f,
			4716.981f,
			0, 0
	    	};
    
    private static final String[][] Units = {
    	
    	{"", "",
    		"Algerian Dinar(DZD)",
    	    "Argentine Peso(ARS)", 
    	    "Australian Dollar(AUD)",
    		"Bahraini Dinar(BHD)",
    		"Bolivian Boliviano(BOB)",
    		"Botswana Pula(BWP)",
    		"Brazilian Real(BRL)",
    		"British Pound(GBP)",
    		"Brunei Dollar(BND)",
    		"Canadian Dollar(CAD)",
    		"Cayman Islands Dollar(KYD)",
    		"Chilean Peso(CLP)",
    		"Chinese Yuan(CNY)",
    		"Colombian Peso(COP)",
    		"Costa Rica Colon(CRC)",
    		"Croatian Kuna(HRK)",
    		"Czech Koruna(CZK)",
    		"Danish Krone(DKK)",
    		"Dominican Peso(DOP)",
    		"Egyptian Pound(EGP)",
    		"El Salvador Colon(SVC)",
    		"Estonian Kroon(EEK)",
    		"Euro(EUR)",
    		"Honduras Lempira(HNL)",
    		"Hong Kong Dollar(HKD)",
    		"Hungarian Forint(HUF)",
    		"Iceland Krona(ISK)",
    		"Indian Rupee(INR)",
    		"Indonesian Rupiah(IDR)",
    		"Israeli Shekel(ILS)",
    		"Jamaican Dollar(JMD)",
    		"Japanese Yen(JPY)",
    		"Jordanian Dinar(JOD)",
    		"Kazakhstan Tenge(KZT)",
    		"Kenyan Shilling(KES)",
    		"Korean Won(KRW)",
    		"Kuwaiti Dinar(KWD)",
    		"Latvian Lat(LVL)",
    		"Lebanese Pound(LBP)",
    		"Lithuanian Lita(LTL)",
    		"Macedonian Denar(MKD)",
    		"Malaysian Ringgit(MYR)",
    		"Mauritius Rupee(MUR)",
    		"Mexican Peso(MXN)",
    		"Moldovan Leu(MDL)",
    		"Moroccan Dirham(MAD)",
    		"Namibian Dollar(NAD)",
    		"Nepalese Rupee(NPR)",
    		"Neth Antilles Guilder(ANG)",
    		"New Zealand Dollar(NZD)",
    		"Nicaragua Cordoba(NIO)",
    		"Nigerian Naira(NGN)",
    		"Norwegian Krone(NOK)",
    		"Omani Rial(OMR)",
    		"Pakistani Rupee(PKR)",
    		"Papua New Guinea Kina(PGK)",
    		"Paraguayan Guarani(PYG)",
    		"Peruvian Nuevo Sol(PEN)",
    		"Philippine Peso(PHP)",
    		"Polish Zloty(PLN)",
    		"Qatar Rial(QAR)",
    		"Russian Rouble(RUB)",
    		"Saudi Arabian Riyal(SAR)",
    		"Seychelles Rupee(SCR)",
    		"Sierra Leone Leone(SLL)",
    		"Singapore Dollar(SGD)",
    		"Slovak Koruna(SKK)",
    		"South African Rand(ZAR)",
    		"Sri Lanka Rupee(LKR)",
    		"Swedish Krona(SEK)",
    		"Turkey Lira(TRY)",
    		"Swiss Franc(CHF)",
    		"Taiwan Dollar(TWD)",
    		"Tanzanian Shilling(TZS)",
    		"Thai Baht(THB)",
    		"Trinidad Dollar(TTD)",
    		"Tunisian Dinar(TND)",
    		"U.S. Dollar(USD)",
    		"UAE Dirham(AED)",
    		"Ugandan Shilling(UGX)",
    		"Ukraine Hryvnia(UAH)",
    		"Uruguayan New Peso(UYU)",
    		"Venezuelan Bolivar(VEB)",
    		"Vietnam Dong(VND)",
    		"Yemen Riyal(YER)",
    		"Zambian Kwacha(ZMK)",
    		"",""},
    		
    	{"", "", "arcminute", "arcsecond", "circle", "deree", "gon", "grad", "mil (Nato)", "mil (Soviet Union)",
    	"mil (Sweden)", "octant", "quadrant", "radian", "revolution", "sextant", "sign", "turn", "",""},
    	
    	{"", "", "acres [ac]", "ares [a]", "circular inches", "hectares", "hides","roods" ,"square centimeters [cm^2]",
    	 "squre feet (US&UK)", "squre feet (US survey)", "squre inches [in^2]", "square kilometers [km^2]", "square meters [m^2]",
    	 "square miles [mi^2]", "square millimeters [mm^2]", "square of timber", "square rods", "square yards", "townships", "", ""},
    	
    	{"", "", "grains/gallon (UK)", "grains/gallon (US)", "grams/cubic centimeters [g/cm^3]", "grams/liter [g/L]", "grams/milliliters [g/mL]",
    	 "kilograms/cubic meters [kg/m^3]", "kilograms/liter [kg/L]", "megagrams/cubic meter [Mg/m^3]", "milligrams/milliliter [mg/mL]",
    	 "milligrams/liter [mg/L]", "ounces/cubic inch [oz/in^3]", "ounces/gallon (UK)", "ounces/gallon (US)", "pounds/cubic inch [lb/in^3]",
    	 "pounds/cubic foot [lb/ft^3]", "pounds/gallon (UK)", "pounds/gallon (US)", "slugs/cubic foot [slug/ft^3]", "tonnes/cubic meter",
    	 "tons (UK)/cubic yard", "tons (US)/cubic yard", "" ,""},
    	 
    	{"", "", "abampere [abA]", "ampere [A]", "biot [Bi]", "centiampere", "coulomb/second", "EMU of current", "ESU of current",
    	 "franklin/second", "gaussian electric current", "gigaampere", "gilbert [Gi]", "kiloampere [kA]", "megaampere",
    	 "microampere", "milliampere [mA]", "milliamp", "nanoampere [nA]", "picoampere [pA]", "siemens volt", "statampere [stA]",
    	 "teraampere", "volt/ohm", "watt/volt", "weber/henry", "", ""},
    	 
    	{"", "", "Btu (th)", "Btu (mean)", "calories (IT) [cal]", "calories (th) [cal]", "calories (mean) [cal]", "calories (15C)",
    	 "calories (20C)", "calories (food)", "centigrade heat units", "electron volts [eV]", "ergs", "foot-pound force [ft lbf]",
    	 "foot poundals", "gigajoules [GJ]", "horsepower hours", "inch-pound force [in lbf]", "joules [J]", "kilocalories (IT)",
    	 "kilocalories (th)", "kilogram-force meters", "kilojoules [kJ]", "kilowatt hours [kWh]", "megajoules [MJ]",
    	 "newton meters [Nm]", "therms", "watt seconds [Ws]", "watt hours [Wh]", "", ""} ,
    	 
    	{"", "", "dynes", "kilograms force [kgf]", "kilonewtons [kN]", "kips", "meganewtons [MN]" ,"newtons [N]" , "pounds force [lbf]",
    	 "poundals [pdl]", "sthenes (=kN)", "tonnes force", "tons force (UK)", "tons force (US)", "", ""},
    	 
    	{"", "", "gallons (UK)/100 miles", "gallons (US)/100 miles", "kilometer/liter [km/L])", "liters/100 kilometer",
    	 "liters/meter [L/m]", "miles/gallon (UK) [mpg]", "miles/gallon (US) [mpg]", "", ""},
    	 
    	{"", "", "astronomical units [AU]", "barleycorns", "cables [cl]", "centimeters [cm]", "chains [ch]", 
    	 "decimeters [dm]", "ells (UK)",  "ems (pica)", "fathoms [fath]", "feet (UK and US) [ft]", "feet (US survey) [ft]", "furlongs [fur]",  
    	 "hands",  "hectometers [hm]",  "inches [in]",  "kilometers [km]",  "light years [ly]", "meters [m]", "micrometers [um]", 
    	 "mil [mi]",  "miles (UK and US) [mi]", "miles (nautical, international)", "miles (nautical, UK)", "millimeters [mm]", 
    	 "nanometers [nm]",  "parsecs [pc]", "picometers [pm]",  "Scandinavian mile", "thou",  "yards [yd]", "" , ""},
    	 
    	{"", "", "carats (metric) [ct]", "cental",  "Earth masses", "grains [gr]", "grams [g]",  "hundredweights",          
    	 "kilograms [kg]", "ounces [oz]", "ounces (troy, precious metals)", "pounds [lbs]",         
    	 "pounds (troy, precious metals)",  "Solar masses", "slugs (g-pounds)", "stones", "tons (UK or long)",
    	 "tons (US or short)", "tonnes [t]", "", ""},
    	 
    	{"", "", "Btu/hour [Btu/h]", "Btu/minute [Btu/min]", "Btu/second [Btu/sec]",  "calories(th)/hour [cal/h]",  "calories(th)/minute [cal/min]",  
    	 "calories(th)/second [cal/s]", "foot pounds-force/minute", "foot pounds-force/second", "gigawatts [GW]", "horsepowers (electric)", 
    	 "horsepowers (international)", "horsepowers (water)", "horsepowers (metric)", "watts [W]", "joules/hour [J/h]",        
    	 "joules/minute [J/min]", "joules/second [J/s]", "kilocalories(th)/hour [kcal/h]", "kilocalories(th)/minute [kcal/min]", "kilogram-force meters/hour", 
    	 "kilogram-force meters/minute", "kilowatts [kW]", "megawatts [MW]", "", ""},
    	 
    	{"", "", "atmospheres [at]", "bars", "centimeters mercury [0C]", "centimeters water", "feet water [ftAq]",
    	 "hectopascals [hPa]", "inches water [inAq]", "inches mercury [inHg]", "kilogram-forces/sq.centimeter", "kilogram-forces/sq.meter",
    	 "kilonewtons/sq.meter", "kilonewtons/sq.millimeter", "kilopascals [kPa]", "kips/sq.inch", "meganewtons/sq.meter",
    	 "meganewtons/sq.millimeter", "meters water", "millibars [mbar]", "millimeters mercury", "millimeters water",
    	 "newtons/sq.centimeter", "newtons/sq.meter", "newtons/sq.millimeter", "pascals [Pa]", "pounds-force/sq.foot",
    	 "pounds-force/sq.inch [psi]", "poundals/sq.foot", "tons (UK)-force/sq.foot", "tons (UK)-force/sq.inch", "tons (US)-force/sq.foot",
    	 "tons (US)-force/sq.inch", "tonnes-force/sq.cm", "tonnes-force/sq.meter", "torr (mm Hg 0C)", "", ""}, 
    	 
    	{"", "", "centimeters/minute [cm/min]",  "centimeters/second [cm/s]", "feet/hour [ft/h]", "feet/minute [f/min]", "feet/second [ft/s]",
    	  "inches/minute [in/min]",  "inches/second [in/s]",  "kilometers/hour [km/h]",  "kilometers/second [km/s]",  "knots [kt]",
    	  "Mach number (ISA/Sea level)",  "meters/hour [m/h]", "meters/minute [m/min]", "meters/second [m/s]", "miles/hour [mi/h]",
    	  "miles/minute [mi/min]", "miles/second [mi/s]", "nautical miles/hour", "Nm/24hr (Volvo Ocean Race)",  "speed of light",
    	  "yards/hour [yd/h]", "yards/minute [yd/min]", "yards/second [yd/s]", "", ""},
    	 
    	{"", "", "Celsius [C]", "Fahrenheit [F]", "Kelvin [K]", "Rankine [R]", "", "" },
  
    	{"", "", "centuries", "days [d]", "decades", "femtoseconds [fs]", "fortnights",
    	  "hours [h]", "microseconds [us]", "millenia", "milliseconds [ms]", "minutes [min]",
    	  "months (Common)", "months (Synodic)", "nanoseconds [ns]", "picoseconds [ps]", "quarters (Common)",
    	  "seconds [s]", "shakes", "weeks", "years (Common) [y]", "years (Average Gregorian)",
    	  "years (Julian)", "years (Leap)", "years (Tropical)", "", ""},
    	  
    	{"", "", "acre foot [ac*ft]", "barrels (oil) [bbl]", "bushels (UK)", "bushels (US)", "centiliters",
    	 "cubic centimeters [cm^3]", "cubic decimeters [dm^3]", "cubic decameters", "cubic feet [ft^3]", "cubic inches [in^3]",
    	 "cubic meters [m^3]", "cubic millimeters [mm^3]", "cubic yards [yd^3]", "cups", "deciliters [dL]",
    	 "fluid ounces (UK)", "fluid ounces (US)", "gallons (UK) [gal]", "gallons, dry (US)", "gallons, liquid (US)",
    	 "liters [L]", "liters (1901-1964)", "milliliters [mL]", "pints (UK) [pt]", "pints, dry (US)",
    	 "pints, liquid (US)", "quarts (UK) [qt]", "quarts, dry (US)", "quarts, liquid (US)", "table spoons",
    	 "tea spoons", "", ""}  
    };   
    
    private static final double[][] formulae = {
    	
    	{   0, 0, 
    		72706.1219,
    		3851.79821,
    		1189.62646,
    		376.97014,
    		7020.00702,
    		6788.86626,
    		1881.00039,
    		614.779294,
    		1438.79924,
    		1093.10046,
    		809.998623,
    		551267.916,
    		6829.9946,
    		2.03665988,
    		584795.322,
    		5149.59576,
    		17775.8817,
    		5209.69002,
    		35950.5321,
    		5528.98571,
    		8749.97813,
    		10949.5445,
    		699.986,
    		18890.0223,
    		7750.91655,
    		190041.809,
    		125643.925,
    		48520.1359,
    		10.0,
    		3820.00153,
    		88051.422,
    		93615.4278,
    		707.699058,
    		150784.077,
    		76051.4108,
    		1.24533001,
    		287.169826,
    		491.299093,
    		1.5015015,
    		2401.30054,
    		43149.9461,
    		3521.49875,
    		31549.7224,
    		13247.8406,
    		11222.4629,
    		7922.2981,
    		7760.72144,
    		75872.5341,
    		1769.99922,
    		1461.13384,
    		19919.9219,
    		154012.013,
    		6036.60598,
    		385.009279,
    		83049.5806,
    		2747.25275,
    		4.97512438,
    		2936.00392,
    		48790.0078,
    		2860.19918,
    		3640.99763,
    		31632.5562,
    		3750.09375,
    		12550.0433,
    		3.55871886,
    		1441.90077,
    		21087.7038,
    		7739.51876,
    		114744.693,
    		7105.70446,
    		1499.99925,
    		1060.79974,
    		32879.5949,
    		1.31926121,
    		34010.135,
    		6279.98694,
    		1322.49942,
    		1000.0,
    		3672.90571,
    		2.05338809,
    		8410.00454,
    		22549.9481,
    		2.14592275,
    		17857142.9,
    		202183.583,
    		4.71698113,
    		0, 0
    	},
    	
    	{0, 0, 1, 60, 0.0000462962962963, 0.016666666666668, 0.01851851851852, 0.01851851851852, 0.29629629629632, 0.2777777777778, 0.29166666666669,
    	 0.0003703703703704, 0.0001851851851852, 0.0002908882086657, 0.0000462962962963, 0.0002777777777778, 0.0005555555555556, 0.0000462962962963, 0,0},
    	
    	{0, 0, 1, 40.468564224000005, 7986573.299424302, 0.4046856422400001, 0.0083440338606186, 4, 40468564.2240002,
    	 43560, 43559.82576030331, 6272640, 0.0040468564224, 4046.8564224,
    	 0.0015625, 4046856422.4000006, 435.6, 160, 4840, 0.0000434027777778, 0, 0},
    	 
    	{0, 0, 1, 0.8326871543417528, 0.0000142539483437, 0.0142539483437, 0.0000142539483437,
    	 0.0142539483437, 0.0000142539483437, 0.0000142539483437, 0.0142539483437,
    	 14.253948343700003, 0.0000082393048653, 0.002285743388642, 0.0019032793490731, 5.149565672e-7,
    	 0.0008898449460641, 0.0001428589546371, 0.0001189549642856, 0.00002766049625, 0.0000142539483443,
    	 0.0000107258093638, 0.000012012906486, 0, 0},
    	 
    	{0, 0, 1, 10, 1, 1000, 10, 1, 29979245368.431435,
    	 29979245368.431435, 29979245368.431435, 1e-8, 12.566370542658102, 0.01, 0.00001,
    	 10000000, 10000, 10000, 1e10, 1e13, 10, 29979245368.431435,
    	 1e-11, 10, 10, 10, 0, 0},
    	  
    	{0, 0, 1, 0.9985604288406716, 251.82717110920032, 251.99569789674948, 251.63364375349042, 251.88733336518703,
    	 252.12224108658745, 0.2518752986144291, 0.5548042517364766, 6.580680193984485e+21, 10543500000.0, 777.6486520904849,
    	 25020.170859041296, 0.00000105435, 0.000392751776854, 9331.783825086704, 1054.35, 0.2518271711092243,
    	 0.2519956978967735, 107.51377891533811, 1.0543500000001005, 0.000292875, 0.00105435 ,
    	 1054.35, 0.0000099933098085, 1054.3500000037889, 0.2928750000010525, 0, 0},
    	
    	{0, 0, 1, 0.000001019716213, 1e-8, 2.2480892e-9, 1e-11, 0.00001, 0.000002248089431,
    	 0.0000723301146433, 1e-8, 1.0197162e-9, 1.0036113e-9, 1.1240447e-9, 0, 0},
    	 
    	{0, 0, 1, 1.200949925504855, 35.400618993464704, 2.824809363318222, 0.0000282480936332,
    	 99.99999999993706, 83.26741846284649, 0, 0}, 
    	
    	{0, 0, 1, 17668424471477.5, 818014818.4601924, 14959855000000.0, 7436483476.641415,
    	 1495985500000.0, 170969771428.57144, 35338518413530.82, 81801481846.01924, 490808891076.1155, 490807909458.3334, 743649834.9638113,
    	 1472426673228.3464, 1495985500, 5889706692913.386, 149598550, 0.000015812916953, 149598549999.76257, 149598549999762620.0,
    	 5889706692904039.0, 92956229.37047641, 80776754.85961123, 80725146.55857162, 149598550000000.0,
    	 149598549999999980000.0, 0.0000048481587966, 1.4959854999999998e+23, 14959855, 5889706692913386.0 , 163602963692.03848, 0, 0},
    	 
    	{0, 0, 1, 0.0000044092452437, 3.3e-29, 3.0864716705882866, 0.2, 0.0000039368261104,
    	 0.0002, 0.0070547923899161, 0.0064301493137256, 0.0004409245243698,
    	 0.0005358457761438, 1.01e-34, 0.0000137043531124, 0.0000314946088836, 1.968413055e-7,
    	 2.204622622e-7, 2e-7, 0 , 0},
    	 
    	{0, 0, 1, 0.0166666600319479, 0.0002777776724648, 252.16434034416835, 4.202739005736138,
    	 0.0700456500956023, 12.969464973226536, 0.2161577495537756, 2.93071e-10, 0.0003928565683646,
    	 0.0003930146848197, 0.0003928339251223, 0.0003984656399167, 0.2930710000000001, 1055.0556000000001,
    	 17.58426, 0.2930710000000001, 0.2521643403441683, 0.0042027390057361, 107.58847283406756,
    	 1.7930973299723454, 0.000293071, 2.93071e-7, 0, 0},
    	
    	{0, 0, 1, 1.01325, 76.000210017852, 1033.227452799886, 33.898538477687,
    	 1013.25, 406.782461732239, 29.921261237637, 1.0332274528, 10332.27452799886,
    	 101.325, 0.000101325, 101.325, 0.014695943006, 0.101325,
    	 1.01325e-7, 10.332274527999, 1013.25, 760.002100178515, 10332.27452799886,
    	 10.1325, 101325, 0.101325, 101325, 2116.228070175439,
    	 14.695949400392, 69968.09744779582, 0.944746435931, 0.00656067287, 1.058114035152,
    	 0.007347982161, 0.001033227453, 10.332274530003, 760.002100325956, 0, 0},
    	
    	{0, 0, 1, 0.016666666667, 1.968500000039, 0.032808398951, 0.000546806649,
    	 0.393699999878, 0.00656167979, 0.0006, 1.66667e-7, 0.000323974082,
    	 4.89774e-7, 0.6, 0.01, 0.000166666667, 0.000372822715,
    	 0.000006213712, 1.03562e-7, 0.000323974082, 0.00777537797, 1e-12,
    	 0.656166666667, 0.010936132983, 0.000182268883, 0, 0},
    	 
    	{0, 0, 1, 2, 3, 4, 0, 0},
    	
    	{0, 0, 1, 36500, 10, 3.1536e+24, 2607.142857142858,
    	 876000, 3.1536e+15, 0.1, 3.1536e+12, 52560000, 
    	 1200, 1236.006501597378, 3.1536e+18, 3.1536e+21, 400,
    	 3.1536e+9, 3.1536e+17, 5214.285714285716, 100, 99.933605755081,
    	 99.931553730322, 99.726775956284, 99.933690573918, 0, 0},
    		
    	{0, 0, 1, 7758.367346938776, 33916.00907448818, 35003.2458775495, 123348183.754752,
    	 1233481837.54752, 1233481.83754752, 1.233481837548, 43560, 75271680,
    	 1233.48183754752, 1233481837547.52, 1613.333333333333, 5213622.857142857, 12334818.375475198,
    	 43412491.615344875, 41708982.85714286, 271328.07259590545, 280025.967020396, 325851.4285714286,
    	 1233481.83754752, 1233447.3010230914, 1233481837.54752, 2170624.5807672436, 2240207.736163168,
    	 2606811.4285714286, 1085312.2903836218, 1120103.868081584, 1303405.7142857143, 83417965.71428572,
    	 250253897.14285713, 0, 0}
    	
    };

}